package com.base.scanner;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.base.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileAdapter extends RecyclerView.Adapter<FileAdapter.FileViewHolder> {

    public static final String FILE_KEY = "file_key";
    private List<File> fileList = new ArrayList<>();
    private Context context;

    public void setNewData(List<File> fileList) {
        this.fileList.clear();
        this.fileList.addAll(fileList);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public FileViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();
        View rootView = LayoutInflater.from(context).inflate(R.layout.list_item_file, parent, false);
        return new FileViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull FileViewHolder holder, int position) {
        File file = fileList.get(position);
        String miniType = FileUtils.getMiniType(file);
        if (!TextUtils.isEmpty(miniType)) {
            if (miniType.startsWith("audio")) {
                holder.tvFileType.setText("audio");
                holder.tvFileType.setBackgroundColor(Color.GREEN);
            } else {
                holder.tvFileType.setText("video");
                holder.tvFileType.setBackgroundColor(Color.BLUE);
            }
        }
        holder.tvFilePath.setText(file.getAbsolutePath());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(miniType)) {
                    if (miniType.startsWith("audio")) {
                        AudioPlayerActivity.start(context, file.getAbsolutePath());
                    } else {
                        VideoPlayerActivity.start(context, file.getAbsolutePath());
                    }
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return fileList.size();
    }

    public static class FileViewHolder extends RecyclerView.ViewHolder {

        private final TextView tvFileType;
        private final TextView tvFilePath;

        public FileViewHolder(@NonNull View itemView) {
            super(itemView);
            tvFileType = itemView.findViewById(R.id.tv_file_type);
            tvFilePath = itemView.findViewById(R.id.tv_file_path);
        }
    }
}
